package cn.nuaa.cms.util;

import java.io.IOException;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * 七牛文件上传工具类
 * 
 * @author giegie
 * 
 */
public class QiniuUtil {
	// 设置好账号的ACCESS_KEY和SECRET_KEY
	private static String ACCESS_KEY = "hM2cBDEM0FTYzpXbigRW90kV12NhhzhFM3jCzurJ";
	private static String SECRET_KEY = "g0HJr2Ltrs0k6tJDY6pDI2aVMUCPSWZDTROLcFMs";
	private static String bucketname = "data";
	private static Auth auth = null;
	private static UploadManager uploadManager = null;
	static {
		auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		uploadManager = new UploadManager();
	}

	// 简单上传，使用默认策略，只需要设置上传的空间名就可以了
	public static String getUpToken() {
		return auth.uploadToken(bucketname);
	}

	/**
	 * 文件上传
	 * 
	 * @param filePath
	 * @param key
	 * @throws IOException
	 */
	public static void upload(String filePath, String key) throws IOException {
		try {
			// 调用put方法上传
			Response res = uploadManager.put(filePath, key, getUpToken());
			// 打印返回的信息
			System.out.println(res.url());
			System.out.println(res.bodyString());
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常的信息
			System.out.println(r.toString());
			try {
				// 响应的文本信息
				System.out.println(r.bodyString());
			} catch (QiniuException e1) {
				// ignore
			}
		}
	}
}
